package com.iworkh.spring.web.mvc.controller;

import com.iworkh.spring.web.mvc.domain.vo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * DataBindController
 *
 * @author: iworkh-沐雨云楼
 * @date: 2019-12-31
 */
@Controller
@RequestMapping("/springmvc")
public class DataBindController {

    @ModelAttribute("student")
    public Student init() {
        System.out.println("DataBindController--init");
        return new Student();
    }

    @RequestMapping(value = "/testBind")
    public String testBind() {
        System.out.println("testBind...");
        return "add";
    }

    @RequestMapping(value = "/testConvertObject")
    public String testConvertObject(@RequestParam("student") Student student) {
        System.out.println("testConvertObject...:" + student);
        return "success";
    }

    // @RequestMapping(value = "/testAdd", method = RequestMethod.POST)
    // public String testAdd(Student student) {
    //     System.out.println("testAdd...:" + student);
    //     return "success";
    // }

    @RequestMapping(value = "/testAdd", method = RequestMethod.POST)
    public String testAdd(@Valid Student student, BindingResult bindingResult) {

        if (bindingResult.getErrorCount() > 0) {
            System.err.println("有错....");
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();

            fieldErrors.forEach(error -> {
                System.err.println(error.getField()+"-----"+error.getDefaultMessage());
            });

            return "add";
        }
        System.out.println("testAdd...:" + student);
        return "success";
    }

    // @InitBinder
    // public void testBind(WebDataBinder binder) {
    //     // 可以设置某些字段不绑定
    //     binder.setDisallowedFields("phone");
    // }

}
